{% extends "base.html" %}

{% block head %}

<title>reSchedule</title>
<script src="{{url_for('static', filename='bootstrap-twipsy.js')}}"></script>
<script src="{{url_for('static', filename='bootstrap-popover.js')}}"></script>
<script src="{{url_for('static', filename='fullcalendar.js')}}"></script>
<script type='text/javascript' src="{{url_for('static', filename='fullcalendar.js') }}"></script>
<link rel="stylesheet" href="{{url_for('static', filename='fullcalendar.css')}}"/>
<script>
  var semester = 201201;
  var courses = [
    {% for c in courses %}
    "{{c}}",
    {% endfor %}
  ];
  
  var free_where = {};

var todate = function(timestamp, weekday, offsetmin) {
  var now = new Date();
  var D = now.getDate();
  var M = now.getMonth();
  var Y = now.getFullYear();
  var H = parseInt(timestamp.substr(0,2), 10);
  var m = parseInt(timestamp.substr(2,2), 10);
  var w = "SMTWRF".indexOf(weekday);
  var x = new Date(Y, M, D + (w-now.getDay()), H, m);
  if(offsetmin != null) {
    y = new Date();
    y.setTime(x.getTime() + (offsetmin*60*1000));
    return y;
  } else
    return x;
}

var render_schedule = function(data) {
  if(data.error) {
    alert("error: " + data.error);
    return;
  }
  var events = [];
  var groupby = {};
  var codes = [];
  $.each(data.response, function(i, e) {
    if(e.btime != null) {
      var ev = {
        title: e.code, 
        start: todate(e.btime, e.day),
        end: todate(e.etime, e.day),
        allDay: false,
        color: '#800517',
        info: e
        };
      events.push(ev);
      if(!groupby[e.code]) {
        groupby[e.code] = [];
        codes.push(e.code);
      }
      groupby[e.code].push(e);
    }
  });
  $("#schedule")
    .fullCalendar("removeEvents")
    .fullCalendar("addEventSource", events)
    .fullCalendar("render");
  $.each(codes, function(i, c) {
    var ul = $("<ul>");
    var title = c + ":" + groupby[c][0].title;
    var x = $("<li>").append(title, ul);
    $("#sections").append(x);
    $.each(groupby[c], function(j, e) {
      $("<li>")
        .append(e.crn + " [" + e.schd + "]")
        .appendTo(ul);
    });
  });
};
var render_free_events = function(data) {
    var events = [];
    if(data.error) {
      alert("error in fetching free rooms: " + data.error);
      return;
    }
    free_where = data.where;
    $.each(data.response, function(i, x) {
      events.push({
        title: x.numlocs + "",
        start: todate(x.btime, x.day),
        end: todate(x.btime, x.day, x.duration),
        allDay: false,
        editable: false,
        color: 'rgba(0,100,0,0.3)',
        info: x
      });
    });
    $("#free")
      .fullCalendar('removeEvents')
      .fullCalendar('addEventSource', events)
      .fullCalendar('render');
};
var render_free_locations = function(data) {
  $("#free-locations").empty();
  console.debug(data);
  if(data.response) {
    $.each(data.response, function(i, x) {
      var li = $('<li>').html(x.location);
      $("#free-locations").append(li);
    });
  }
}

var make_calendar = function(opt) {  
  var div = opt.div;
  var eraseheader = opt.eraseheader;
  var renderer = opt.renderer;
  var onclick = opt.onclick;
  var f;
  if(renderer != null) {
    f = function(ev, elem) {
      $(elem).addClass("calendar-event").data("_id", ev._id);
      return renderer(ev, elem);
    };
  } else {
    f = function(ev, elem) {
      $(elem).addClass("calendar-event").data("_id", ev._id);
    }
  }
  var o = {
    header: {
      left: '',
      center: '',
      right: ''},
    defaultView: 'agendaWeek',
    allDaySlot: false,
    minTime: 8,
    maxTime: 23,
    aspectRatio: 0.5,
    events: [],
    eventRender: f
  };
  if(onclick) {
    o.eventClick = onclick;
  }
  $(div).fullCalendar(o);
  // Remove date from the weekday heading
  $("thead .fc-widget-header", $(div)).each(function(i, e) {
    if(eraseheader == 'erase')
      $(this).html("-");
    else {
      var text = $(this).text();
      if(text.length > 0) $(this).html(text.substr(0, 3));
    }
  });
  // Remove scrolling
  $('.fc-view-agendaWeek > div > div', div).css('overflow-y', 'hidden');
  $('.fc-agenda-gutter', div).css('width', 0);
  // Remove background coloring for inner
  $(".fc-event-inner").css('background-color', null);
};

var fetch_schedule = function() {
  return $.ajax({
      url: "{{url_for('schedule')}}", 
      data: {semester: semester, courses: courses},
      dataType: 'json',
      success: render_schedule
  });
};

var fetch_free = function(btime, day) {
  var data, f;
  if(btime) {
    data = {
      semester: semester,
      btime: btime,
      day: day,
      campus: free_where.campus,
      location: free_where.location,
      duration: free_where.duration,
      capacity: free_where.capacity,
      detail: 1
    };
    f = render_free_locations;
  } else {
    data = {semester: semester, searchbar: $("#searchfree").val()};
    f = render_free_events;
  }
  return $.ajax({
        url: "{{url_for('free')}}",
        data: data,
        dataType: 'json',
        success: f
  });
};
var refresh_free = function(btime, day) {
  $("div.message").html("Loading free information...");
  $.when(fetch_free(btime, day)).then(function() {
    $("div.message").empty();
  });
};

$(document).ready(function() {
  
  $("#back").click(function(e) {
    window.location.href = "{{(url_for('index'))}}";
  });
  make_calendar({
    div: "#schedule",  
    renderer: function(ev, elem) {
      $(elem).attr({
        title: ev.title,
        'data-content': 
          "<i>" + ev.info.title + "</i>," + 
          "<b>" + ev.info.schd + "</b> at " + 
          "<span style='font-size:120%'>" + ev.info.location + "</span>"
      });
      $(elem).popover({html: true});
    }
  });
  make_calendar({
    div: "#free", 
    eraseheader: 'erase',
    onclick: function(event, jsevent, view) {
      refresh_free(event.info.btime, event.info.day);
    }
  });

  $("div.message").html("Loading schedule information...");
  $.when(fetch_schedule(), fetch_free()).done(function() {
    $("div.message").empty();
  });

  $("#overlay").click(function(e) {
    $(this).toggleClass('success');
    if($(this).hasClass('success'))
      $("#free").css({
        opacity: 1.0,
        'z-index': 100
      });
    else
      $("#free").css({
        opacity: 0.4,
        'z-index': 1});
  });

  $("#searchfree").keypress(function(e) {
    if(e.which == 13) {
      e.preventDefault();
      refresh_free();
    }
  });

  $("#free .calendar-event").live('click', function() {
    $(this).toggleClass("selected-free");
    // CSS control doesn't work, so need to do this automatically
    if($(this).hasClass("selected-free")) {
      $(this).css('background', '#000');
    } else {
      $(this).css('background', 'rgba(0,100,0, 0.3)');
    }
  });
});
 
</script>
{% endblock %}

{% block topbar %}
<div class="topbar-wrapper" style="z-index: 5;">
  <div class="topbar" data-dropdown="dropdown" >
    <div class="topbar-inner">
      <div class="container">
        <h3><a href="#">UOIT RE-Schedule</a></h3>
        <ul class="nav">
          <li class="active"><a href="#">Course Selection</a></li>
          <li><a href="#">Conflicts</a></li>
        </ul>
        <ul class="nav secondary-nav">
          <li class="dropdown">
            <a href="#" class="dropdown-toggle">Dropdown</a>
            <ul class="dropdown-menu">
              <li><a href="#">Secondary link</a></li>
              <li><a href="#">Something else here</a></li>
            </ul>
          </li>
        </ul>
      </div>
    </div><!-- /topbar-inner -->
  </div><!-- /topbar -->
</div><!-- /topbar-wrapper -->
{% endblock %}
  
{% block body %}
  
  <div class="container">
    <div class="content">
      <div class="page-header">
        <h1>Scheduling <small>Move around the courses to view free times and rooms</small></h1>
      </div>
      <div class="span16">
                    <div class="toolbar">
              <input type="text" class="xlarge" id="searchfree"></input>
              <button class="btn" id="overlay">Free Locations</button>
              <div class="message"></div>
            </div>
        <div class="row">
          <div class="span5">
            <h2>Selected courses</h2>
            <button class="btn danger" id="back">    Back    </button> 
            <div class="sections">
              <b>sections</b>
              <ul id="sections"></ul>
            </div>
            <div class="free-locations">
              <b>free locations</b>
              <ul id="free-locations"></ul>
            </div>
            <br/>
          </div>
          <div class="span11">
            <div class="content">
              <div class="calendars">
                <div class="calendar"><div id="schedule"></div></div>
                <div class="calendar"><div id="free"></div></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <footer>
      <p>&copy; December 26 2011</p>
    </footer>


{% endblock %}